package com.haha.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.utils.PageUtils;
import com.haha.common.utils.Query;
import com.haha.gulimall.product.dao.CategoryDao;
import com.haha.gulimall.product.entity.CategoryEntity;
import com.haha.gulimall.product.service.CategoryBrandRelationService;
import com.haha.gulimall.product.service.CategoryService;
import com.haha.gulimall.product.vo.Category2VO;
import com.mysql.cj.util.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private RedissonClient redissonClient;

    /**
     * 删除方法重写
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 检查当前菜单是否被应用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 根据一个菜单id，返回他的所有路径上的id
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] getCategroyPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        findCateGoryPath(catelogId, path);
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    /**
     * 冗余字段处理
     *
     * @param category
     */
    @Override
    @Transactional
    @CacheEvict(value = "categorys", allEntries =true)
    public void updateDetail(CategoryEntity category) {
        System.out.println("进行了更新目录");
        CategoryEntity byId = this.getById(category.getCatId());
        this.updateById(category);
        if (!category.getName().equals(byId.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
            //todo 其他表的冗余字段也需要更新
        }
    }

    @Override
    @Cacheable(value = "categorys",key = "#root.methodName")
    public Map<String, List<Category2VO>> getCategroyJson() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);
        List<CategoryEntity> level1s = getParent_cid(categoryEntities, 0L);
        Map<String, List<Category2VO>> categoryJson = level1s.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> level2s = getParent_cid(categoryEntities, v.getCatId());
            List<Category2VO> category2VOS = null;
            if (level2s != null) {
                category2VOS = level2s.stream().map(lv2 -> {
                    Category2VO category2VO = new Category2VO(v.getCatId().toString(), null, lv2.getCatId().toString(), lv2.getName());
                    List<CategoryEntity> level3Category = getParent_cid(categoryEntities, lv2.getCatId());
                    List<Category2VO.Category3> category3s = null;
                    if (level3Category != null) {
                        category3s = level3Category.stream().map(lev3 -> {
                            Category2VO.Category3 category3 = new Category2VO.Category3(lv2.getCatId().toString(), lev3.getCatId().toString(), lev3.getName());
                            return category3;
                        }).collect(Collectors.toList());
                    }
                    category2VO.setCatalog3List(category3s);
                    return category2VO;
                }).collect(Collectors.toList());
            }
            return category2VOS;
        }));
        return categoryJson;
    }
    public Map<String, List<Category2VO>> getCategroyJson2() {
        String categroyJson = redisTemplate.opsForValue().get("categroyJson");
        if (StringUtils.isNullOrEmpty(categroyJson)) {
            Map<String, List<Category2VO>> categroyJsonFromDb = getCategroyJsonFromDbWithRedisLock();

            return categroyJsonFromDb;
        }
        Map<String, List<Category2VO>> stringListMap = JSON.parseObject(categroyJson, new TypeReference<Map<String, List<Category2VO>>>() {
        });
        return stringListMap;

    }

    public Map<String, List<Category2VO>> getCategroyJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("CategroyJson-lock");
        lock.lock();

        Map<String, List<Category2VO>> dataFromDb = null;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;


    }

    public Map<String, List<Category2VO>> getCategroyJsonFromDbWithRedisLock() {
        //需设置过期时间，以防意外断电锁还被占着，要确保设置过期时间与设置锁为原子操作
        String uuid = UUID.randomUUID().toString();
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300L, TimeUnit.MILLISECONDS);
        if (aBoolean) {
            Map<String, List<Category2VO>> dataFromDb = null;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

            }
            return dataFromDb;

        } else {
            return getCategroyJsonFromDbWithRedisLock();
        }


    }

    private Map<String, List<Category2VO>> getDataFromDb() {
        String categroyJson = redisTemplate.opsForValue().get("categroyJson");
        if (!StringUtils.isNullOrEmpty(categroyJson)) {
            Map<String, List<Category2VO>> stringListMap = JSON.parseObject(categroyJson, new TypeReference<Map<String, List<Category2VO>>>() {
            });
            return stringListMap;
        }


        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

        List<CategoryEntity> level1s = getParent_cid(categoryEntities, 0L);
        Map<String, List<Category2VO>> categoryJson = level1s.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> level2s = getParent_cid(categoryEntities, v.getCatId());
            List<Category2VO> category2VOS = null;
            if (level2s != null) {
                category2VOS = level2s.stream().map(lv2 -> {
                    Category2VO category2VO = new Category2VO(v.getCatId().toString(), null, lv2.getCatId().toString(), lv2.getName());
                    List<CategoryEntity> level3Category = getParent_cid(categoryEntities, lv2.getCatId());
                    List<Category2VO.Category3> category3s = null;
                    if (level3Category != null) {
                        category3s = level3Category.stream().map(lev3 -> {
                            Category2VO.Category3 category3 = new Category2VO.Category3(lv2.getCatId().toString(), lev3.getCatId().toString(), lev3.getName());
                            return category3;
                        }).collect(Collectors.toList());
                    }
                    category2VO.setCatalog3List(category3s);
                    return category2VO;
                }).collect(Collectors.toList());
            }
            return category2VOS;
        }));
        String s = JSON.toJSONString(categoryJson);
        redisTemplate.opsForValue().set("categroyJson", s);
        return categoryJson;
    }

    public Map<String, List<Category2VO>> getCategroyJsonFromDbWithLocalLock() {
        synchronized (this) {
            String categroyJson = redisTemplate.opsForValue().get("categroyJson");
            if (!StringUtils.isNullOrEmpty(categroyJson)) {
                Map<String, List<Category2VO>> stringListMap = JSON.parseObject(categroyJson, new TypeReference<Map<String, List<Category2VO>>>() {
                });
                return stringListMap;
            }


            List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

            List<CategoryEntity> level1s = getParent_cid(categoryEntities, 0L);
            Map<String, List<Category2VO>> categoryJson = level1s.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                List<CategoryEntity> level2s = getParent_cid(categoryEntities, v.getCatId());
                List<Category2VO> category2VOS = null;
                if (level2s != null) {
                    category2VOS = level2s.stream().map(lv2 -> {
                        Category2VO category2VO = new Category2VO(v.getCatId().toString(), null, lv2.getCatId().toString(), lv2.getName());
                        List<CategoryEntity> level3Category = getParent_cid(categoryEntities, lv2.getCatId());
                        List<Category2VO.Category3> category3s = null;
                        if (level3Category != null) {
                            category3s = level3Category.stream().map(lev3 -> {
                                Category2VO.Category3 category3 = new Category2VO.Category3(lv2.getCatId().toString(), lev3.getCatId().toString(), lev3.getName());
                                return category3;
                            }).collect(Collectors.toList());
                        }
                        category2VO.setCatalog3List(category3s);
                        return category2VO;
                    }).collect(Collectors.toList());
                }
                return category2VOS;
            }));
            String s = JSON.toJSONString(categoryJson);
            redisTemplate.opsForValue().set("categroyJson", s);
            return categoryJson;
        }

    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> entities, Long parentId) {
        return entities.stream().filter(item -> item.getParentCid().equals(parentId)).collect(Collectors.toList());
    }

    /**
     * 递归的找他的路径
     *
     * @param catelogId
     * @param path
     * @return
     */
    private List<Long> findCateGoryPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId != null) {
            if (byId.getParentCid() != 0) {
                findCateGoryPath(byId.getParentCid(), path);
            }
        }

        return path;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> collect = categoryEntities.stream().filter(a -> a.getParentCid() == 0)
                .map(a -> {
                    a.setChildren(getChilds(a, categoryEntities));
                    return a;
                }).sorted((a, b) -> {
                    return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
                }).collect(Collectors.toList());

        return collect;
    }

    private List<CategoryEntity> getChilds(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(a -> a.getParentCid().equals(root.getCatId()))
                .map(a -> {
                    a.setChildren(getChilds(a, categoryEntities));
                    return a;
                }).sorted((a, b) -> {
                    return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
                }).collect(Collectors.toList());
        return collect;

    }

    @Cacheable(value = {"categorys"},key = "#root.method.name")
    public List<CategoryEntity> getCategroyLevel1() {
        System.out.println("获取一级分类。。。。。。");
        QueryWrapper<CategoryEntity> qw = new QueryWrapper<>();
        qw.eq("parent_cid", 0);
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(qw);
        return categoryEntities;
    }


}